<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Posts extends CI_Model
{
	
	function __construct()
	{
		parent::__construct();

	}

	// If $postId is NULL, gets all posts, otherwise get single post from db 
	// returns $post[]
	public function get_posts($postId)
	{
		$post=array();
		if ($postId !== null){		
			$query = $this->db->get_where('posts', array('id' => $postId));
			if ($query->num_rows() == 1) {	
				foreach($query->result() as $row){
				$post['id'] = $row->id;
				$post['title'] = $row->title;
				$post['summary'] = $row->summary;
				$post['content'] = $row->content;
                $post['created'] = $row->created;
                $post['img_url'] = $row->img_url;
				}
				return $post;
			}	
		} else {
			$query = $this->db->get('posts');
			if ($query->num_rows() !== 0 ){
				foreach($query->result() as $row){
				$post['id'][] = $row->id;
				$post['title'][] = $row->title;
				$post['summary'][] = $row->summary;
				$post['content'][] = $row->content;
                $post['created'][] = $row->created;
                $post['img_url'][] = $row->img_url;
				}
				return $post;
			}
			
		}		
	}

	function insert_post($data){
        $data['updated'] = date('Y-m-d H:i:s');
		$this->db->insert('posts', $data);
		return;
	}

	function update_post($postId,$data){
		$id = $postId;
        $data['updated'] = date('Y-m-d H:i:s');
       	$this->db->where('id',$id);
		$this->db->update('posts', $data);
		return;
	}

	function delete_post($postId){
		$id = $postId;
       		$this->db->delete('posts',array('id' => $id));
		return;
	}
}
